import React, { useState, useMemo } from 'react'
import {
  Table,
  Card,
  Space,
  Button,
  Tooltip,
  Typography,
  Tag,
  Input,
  Select,
  Pagination,
  Empty,
  Spin,
  message,
} from 'antd'
import {
  DownloadOutlined,
  CopyOutlined,
  SearchOutlined,
  FilterOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  TableOutlined,
} from '@ant-design/icons'
import { ColumnsType } from 'antd/es/table'
import { copyToClipboard, downloadFile, formatFileSize } from '@/utils'

const { Text, Title } = Typography
const { Search } = Input
const { Option } = Select

export interface ExecutionResult {
  columns: Array<{
    name: string
    type: string
    nullable?: boolean
  }>
  rows: any[][]
  total_rows: number
  affected_rows?: number
  execution_time: number
  query_id?: string
}

interface ExecutionResultTableProps {
  result: ExecutionResult | null
  loading?: boolean
  error?: string | null
  onExport?: (format: 'csv' | 'excel' | 'json') => void
  maxHeight?: number
  showPagination?: boolean
  pageSize?: number
}

const ExecutionResultTable: React.FC<ExecutionResultTableProps> = ({
  result,
  loading = false,
  error = null,
  onExport,
  maxHeight = 600,
  showPagination = true,
  pageSize = 100,
}) => {
  const [searchText, setSearchText] = useState('')
  const [filterColumn, setFilterColumn] = useState<string>('')
  const [currentPage, setCurrent] = useState(1)
  const [isFullscreen, setIsFullscreen] = useState(false)

  // 构建表格列定义
  const columns: ColumnsType<any> = useMemo(() => {
    if (!result?.columns) return []

    return result.columns.map((col, index) => ({
      title: (
        <div>
          <div style={{ fontWeight: 'bold' }}>{col.name}</div>
          <div style={{ fontSize: '11px', color: '#666', fontWeight: 'normal' }}>
            {col.type}
            {col.nullable && <Tag size="small" color="orange" style={{ marginLeft: 4 }}>NULL</Tag>}
          </div>
        </div>
      ),
      dataIndex: index,
      key: `col_${index}`,
      width: Math.max(120, Math.min(200, col.name.length * 8 + 60)),
      ellipsis: {
        showTitle: false,
      },
      render: (value: any) => (
        <Tooltip title={value?.toString() || 'NULL'} placement="topLeft">
          <div style={{ 
            maxWidth: '100%',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}>
            {value === null || value === undefined ? (
              <Text type="secondary" italic>NULL</Text>
            ) : (
              <Text>{String(value)}</Text>
            )}
          </div>
        </Tooltip>
      ),
      sorter: (a: any, b: any) => {
        const aVal = a[index]
        const bVal = b[index]
        
        if (aVal === null || aVal === undefined) return -1
        if (bVal === null || bVal === undefined) return 1
        
        if (typeof aVal === 'number' && typeof bVal === 'number') {
          return aVal - bVal
        }
        
        return String(aVal).localeCompare(String(bVal))
      },
      filteredValue: filterColumn === col.name ? [searchText] : null,
      onFilter: (value, record) => {
        if (!value) return true
        const cellValue = record[index]
        return String(cellValue || '').toLowerCase().includes(String(value).toLowerCase())
      },
    }))
  }, [result?.columns, filterColumn, searchText])

  // 构建表格数据
  const tableData = useMemo(() => {
    if (!result?.rows) return []
    
    return result.rows.map((row, rowIndex) => ({
      key: rowIndex,
      ...row.reduce((acc, cell, cellIndex) => {
        acc[cellIndex] = cell
        return acc
      }, {} as any)
    }))
  }, [result?.rows])

  // 过滤数据
  const filteredData = useMemo(() => {
    if (!searchText || !filterColumn) return tableData
    
    const columnIndex = result?.columns.findIndex(col => col.name === filterColumn)
    if (columnIndex === -1) return tableData
    
    return tableData.filter(row => {
      const cellValue = row[columnIndex!]
      return String(cellValue || '').toLowerCase().includes(searchText.toLowerCase())
    })
  }, [tableData, searchText, filterColumn, result?.columns])

  // 分页数据
  const paginatedData = useMemo(() => {
    if (!showPagination) return filteredData
    
    const start = (currentPage - 1) * pageSize
    const end = start + pageSize
    return filteredData.slice(start, end)
  }, [filteredData, currentPage, pageSize, showPagination])

  // 复制表格数据
  const handleCopyData = async () => {
    if (!result?.rows || result.rows.length === 0) {
      message.warning('没有数据可复制')
      return
    }

    try {
      // 构建CSV格式的数据
      const headers = result.columns.map(col => col.name).join('\t')
      const rows = result.rows.map(row => row.join('\t')).join('\n')
      const csvData = `${headers}\n${rows}`
      
      const success = await copyToClipboard(csvData)
      if (success) {
        message.success('数据已复制到剪贴板')
      } else {
        message.error('复制失败')
      }
    } catch (error) {
      message.error('复制失败')
    }
  }

  // 导出数据
  const handleExport = (format: 'csv' | 'excel' | 'json') => {
    if (!result?.rows || result.rows.length === 0) {
      message.warning('没有数据可导出')
      return
    }

    onExport?.(format)
  }

  // 切换全屏
  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen)
  }

  if (loading) {
    return (
      <Card>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: 200 
        }}>
          <Spin size="large" />
          <Text style={{ marginLeft: 16 }}>正在执行查询...</Text>
        </div>
      </Card>
    )
  }

  if (error) {
    return (
      <Card>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={
            <div>
              <Text type="danger">查询执行失败</Text>
              <div style={{ marginTop: 8, color: '#ff4d4f', fontSize: 12 }}>
                {error}
              </div>
            </div>
          }
        />
      </Card>
    )
  }

  if (!result) {
    return (
      <Card>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="暂无查询结果"
        />
      </Card>
    )
  }

  const cardStyle = isFullscreen ? {
    position: 'fixed' as const,
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1000,
    margin: 0,
    borderRadius: 0,
  } : {}

  return (
    <Card 
      style={cardStyle}
      bodyStyle={{ 
        padding: 0,
        height: isFullscreen ? '100vh' : 'auto',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* 工具栏 */}
      <div style={{ 
        padding: '12px 16px', 
        borderBottom: '1px solid #f0f0f0',
        background: '#fafafa',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Space>
              <Text strong>
                <TableOutlined /> 查询结果
              </Text>
              <Tag color="blue">
                {result.total_rows.toLocaleString()} 行
              </Tag>
              <Tag color="green">
                {result.execution_time}ms
              </Tag>
              {result.affected_rows !== undefined && (
                <Tag color="orange">
                  影响 {result.affected_rows} 行
                </Tag>
              )}
            </Space>
          </div>
          
          <Space>
            {/* 搜索和过滤 */}
            <Select
              placeholder="选择列"
              style={{ width: 120 }}
              value={filterColumn}
              onChange={setFilterColumn}
              allowClear
            >
              {result.columns.map(col => (
                <Option key={col.name} value={col.name}>
                  {col.name}
                </Option>
              ))}
            </Select>
            
            <Search
              placeholder="搜索..."
              style={{ width: 200 }}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              disabled={!filterColumn}
            />
            
            {/* 操作按钮 */}
            <Tooltip title="复制数据">
              <Button
                icon={<CopyOutlined />}
                onClick={handleCopyData}
              />
            </Tooltip>
            
            <Tooltip title="导出数据">
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('csv')}
              />
            </Tooltip>
            
            <Tooltip title={isFullscreen ? '退出全屏' : '全屏显示'}>
              <Button
                icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                onClick={toggleFullscreen}
              />
            </Tooltip>
          </Space>
        </div>
      </div>

      {/* 表格内容 */}
      <div style={{ 
        flex: 1, 
        overflow: 'auto',
        maxHeight: isFullscreen ? 'calc(100vh - 120px)' : maxHeight,
      }}>
        <Table
          columns={columns}
          dataSource={paginatedData}
          pagination={false}
          scroll={{ 
            x: Math.max(800, columns.length * 150),
            y: isFullscreen ? 'calc(100vh - 180px)' : maxHeight - 100,
          }}
          size="small"
          bordered
          rowClassName={(record, index) => 
            index % 2 === 0 ? 'table-row-even' : 'table-row-odd'
          }
        />
      </div>

      {/* 分页 */}
      {showPagination && filteredData.length > pageSize && (
        <div style={{ 
          padding: '12px 16px', 
          borderTop: '1px solid #f0f0f0',
          background: '#fafafa',
          textAlign: 'center',
        }}>
          <Pagination
            current={currentPage}
            total={filteredData.length}
            pageSize={pageSize}
            onChange={setCurrent}
            showSizeChanger={false}
            showQuickJumper
            showTotal={(total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            }
          />
        </div>
      )}
    </Card>
  )
}

export default ExecutionResultTable